在 Python 中,while 迴圈會根據條件重複執行代碼,只要條件為 True,迴圈就會繼續,直到條件變為 False 才結束。while 適合用在需要根據條件持續重複操作的情況,例如用戶輸入、等待事件等。
while() 基本語法while 條件:
迴圈內的代碼
x = 0
while x < 5:
print(x)
x += 1 # 每次增加 x 防止無限迴圈
break)while True:
user_input = input("輸入 'exit' 來退出: ")
if user_input == "exit":
break # 跳出迴圈
continue 跳過當前迴圈x = 0
while x < 5:
x += 1
if x == 3:
continue # 略過當 x 等於 3
print(x)
while 搭配 elsex = 0
while x < 5:
x += 1
else:
print("迴圈結束")